package com.study.lxy.springcloud.uclient.service.impl;


import com.study.lxy.springcloud.common.exception.BusiException;
import com.study.lxy.springcloud.common.utils.PasswordUtil;
import com.study.lxy.springcloud.common.utils.UUIDUtils;
import com.study.lxy.springcloud.uclient.constants.RespCodeEnum;
import com.study.lxy.springcloud.uclient.dao.ClientUserDao;
import com.study.lxy.springcloud.uclient.entity.ClientUser;
import com.study.lxy.springcloud.uclient.service.NewRegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class NewRegisterServiceImpl implements NewRegisterService{
    private static Logger logger = LoggerFactory.getLogger(NewRegisterServiceImpl.class);

    @Autowired
    private ClientUserDao clientUserDao;
    @Override
    public void newRegister(ClientUser user) {
        logger.info("newRegisterService.newRegister start,user={}",user);
        paramCheck(user);
        busiPreCheck(user);
        passwordWithSalt(user);
        createUser(user);
        logger.info("newRegisterService.newRegister success,clientid={}",user.getClientId());
    }

    private void paramCheck(ClientUser user) {
        if(StringUtils.isEmpty(user.getIdNo())){
            throw new BusiException(RespCodeEnum.PARM_INVILD,"身份证号必输");
        }
        if(StringUtils.isEmpty(user.getMobile())){
            throw new BusiException(RespCodeEnum.PARM_INVILD,"手机号必输");
        }
        if(StringUtils.isEmpty(user.getPassword())){
            throw new BusiException(RespCodeEnum.PARM_INVILD,"密码必输");
        }
        if(StringUtils.isEmpty(user.getTrueName())){
            throw new BusiException(RespCodeEnum.PARM_INVILD,"姓名必输");
        }
    }

    private void busiPreCheck(ClientUser user){
        checkIdNoUsed(user);
        checkMobileUsed(user);
    }

    private void checkIdNoUsed(ClientUser user){
        List<ClientUser> userList = clientUserDao.queryUserByIdNo(user.getIdNo());
        if(!CollectionUtils.isEmpty(userList)){
            throw new BusiException(RespCodeEnum.IDNO_USED);
        }
    }

    private void checkMobileUsed(ClientUser user){
        List<ClientUser> userList = clientUserDao.queryUserByMobileNo(user.getMobile());
        if(!CollectionUtils.isEmpty(userList)){
            throw new BusiException(RespCodeEnum.MOBILE_USED);
        }
    }

    private void passwordWithSalt(ClientUser user){

        String salt = UUIDUtils.getUUID();
        String hashedPsw = PasswordUtil.getHashWithSaltPassword(user.getPassword(),salt);
        user.setSalt(salt);
        user.setPassword(hashedPsw);
    }

    private void createUser(ClientUser user){
        clientUserDao.insertUser(user);
    }
}
